<template>
  <div class="data-form">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑' : '' }}{{ modelDisplayName }}</h2>

    </div>

    <!-- 错误提示 -->
    <el-card v-if="error" class="error-card">
      <el-alert :title="error" type="error" show-icon :closable="false" />
      <div class="error-actions">
        <el-button @click="retryLoading" type="primary">重试</el-button>

      </div>
    </el-card>

    <!-- 加载状态 -->
    <el-card v-else-if="loading" class="loading-card">
      <div class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
    </el-card>

    <!-- 表单内容 -->
    <el-card v-else class="form-card">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" :disabled="mode === 'view'">
        <!-- 调试信息 -->
        <div v-if="showDebug" class="debug-info">
          <h4>调试信息</h4>
          <p>模型名称: {{ modelName }}</p>
          <p>记录ID: {{ recordId || '新建' }}</p>
          <p>字段数量: {{ fields.length }}</p>
          <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
          <el-button @click="showDebug = false" size="small">隐藏调试信息</el-button>
        </div>

        <!-- 表单字段 -->
        <template v-if="fields.length > 0">
          <el-form-item v-for="field in fields" :key="field.name" :label="field.label || field.name" :prop="field.name">
            <!-- 根据字段类型渲染不同的输入组件 -->
            <template v-if="field.type === 'string'">
              <el-input v-model="formData[field.name]"
                :placeholder="mode === 'view' ? '' : `请输入${field.label || field.name}`" />
            </template>

            <template v-else-if="field.type === 'number'">
              <el-input-number v-model="formData[field.name]"
                :placeholder="mode === 'view' ? '' : `请输入${field.label || field.name}`" style="width: 100%" />
            </template>

            <template v-else>
              <el-input v-model="formData[field.name]"
                :placeholder="mode === 'view' ? '' : `请输入${field.label || field.name}`" />
            </template>
          </el-form-item>
        </template>

        <el-form-item v-else>
          <el-alert title="没有可用的字段" type="warning" show-icon :closable="false" />
        </el-form-item>

        <!-- 表单操作 -->
        <div class="form-actions">
          <el-button @click="$emit('cancel')">
            {{ mode === 'view' ? '返回' : '取消' }}
          </el-button>
          <el-button v-if="mode !== 'view'" type="primary" @click="handleSubmit" :loading="loading">
            保存
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElSegmented } from 'element-plus'
import { useDataStore } from '../../stores/data'
const dataStore = useDataStore()  // 添加这行
const props = defineProps({
  mode: {
    type: String,
    default: 'create'
  },
  fields: {
    type: Array,
    required: true
  },
  record: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['submit', 'cancel','create'])

const route = useRoute()
const router = useRouter()

const modelName = ref('')
const recordId = computed(() => {
  if (props.record.id) {
    return props.record.id;
  }

})
const isEdit = ref(false)

const loading = ref(true)
const submitting = ref(false)
const error = ref(null)
const showDebug = ref(false)

const modelData = ref(null)
const fields = ref([])
const modelDisplayName = computed(() => modelData.value?.displayName || modelName.value || '数据')

const formData = ref({})
const rules = computed(() => {
  if (props.mode === 'view') return {}

  return props.fields.reduce((acc, field) => {
    if (field.required) {
      acc[field.name] = [{
        required: true,
        message: `请输入${field.label || field.name}`,
        trigger: 'blur'
      }]
    }
    return acc
  }, {})
})

const formRef = ref(null)

onMounted(async () => {
  console.log('DataForm组件已挂载')
  console.log('路由参数:', route.params)

  // 设置模型名称
  modelName.value = route.params.model
  console.log(modelName);
  // 设置记录ID（如果存在）
  if (route.params) {
    // recordId.value = route.params.i
    console.log(props.mode)
    console.log('预览模式')
  } else {
    isEdit.value = false
    console.log('创建模式')
  }

  // 加载数据
  await loadData()
})

async function loadData() {
  error.value = null
  loading.value = true
  showDebug.value = true // 自动显示调试信息

  try {
    console.log('开始加载数据...')

    // 创建一个带超时的axios实例
    const axiosWithTimeout = axios.create({
      timeout: 5000 // 5秒超时
    })

    // 加载模型
    const model = await loadModelData()
    modelData.value = model
    // 确保字段已正确解析
    if (typeof model.fields === 'string') {
      try {
        model.fields = JSON.parse(model.fields)
      } catch (err) {
        console.error('解析字段失败:', err)
        model.fields = []
      }
    }

    fields.value = Array.isArray(model.fields) ? model.fields : []

    console.log('设置字段:', fields.value)

    // 初始化表单数据
    initFormData()

    // 如果是编辑模式，加载记录
    if (isEdit.value) {
      console.log('编辑模式，加载记录数据，ID:', recordId.value)

      // 尝试从列表API获取所有记录，然后找到匹配ID的记录
      try {
        console.log('尝试从列表API获取记录')
        const listResponse = await axiosWithTimeout.get(`/api/data/${modelName.value}`)
        console.log('列表API响应:', listResponse.data)

        let records = []

        if (listResponse.data.items) {
          if (Array.isArray(listResponse.data.items)) {
            records = listResponse.data.items
          } else if (typeof listResponse.data.items === 'object') {
            records = Object.values(listResponse.data.items)
          }
        } else if (Array.isArray(listResponse.data)) {
          records = listResponse.data
        }

        console.log('提取的记录列表:', records)

        // 找到匹配ID的记录
        const record = records.find(r => r && r.id == recordId.value)
        if (record) {
          console.log('找到匹配ID的记录:', record)
          fillFormData(record)
        } else {
          console.warn('未找到匹配ID的记录')
        }
      } catch (err) {
        console.error('从列表API获取记录失败:', err)
      }
    }

    // 生成表单验证规则
    generateFormRules()

    console.log('数据加载完成')
  } catch (err) {
    console.error('加载数据失败:', err)
    error.value = err.message || '加载数据失败'
  } finally {
    loading.value = false

  }
}

async function loadModelData() {
  console.log('开始加载模型数据:', modelName.value)

  try {
    // 使用正确的API路径获取所有模型
    const response = await axios.get('/api/models')
    console.log('模型列表响应:', response.data)

    if (!Array.isArray(response.data)) {
      throw new Error('API返回的模型数据格式不正确')
    }

    // 从列表中找到当前模型
    const model = response.data.find(m => m.name === modelName.value)

    if (!model) {
      throw new Error(`未找到名称为 "${modelName.value}" 的模型`)
    }


    // 处理fields字段
    if (typeof model.fields === 'string') {
      try {
        console.log('解析fields字符串:', model.fields)
        model.fields = JSON.parse(model.fields)
        console.log('解析后的fields:', model.fields)
      } catch (err) {
        console.error('解析fields字符串失败:', err)
        throw new Error('模型字段格式错误')
      }
    }

    if (!Array.isArray(model.fields)) {
      console.warn('模型fields不是数组:', model.fields)
      model.fields = []
    }

    // 确保每个字段都有必要的属性
    model.fields = model.fields.map(field => {
      return {
        name: field.name || '',
        displayName: field.displayName || field.name || '',
        type: field.type || 'string',
        required: !!field.required,
        description: field.description || '',
        ...field
      }
    })

    console.log('处理后的模型字段:', model.fields)

    return model
  } catch (err) {
    console.error('加载模型失败:', err)
    throw new Error(`加载模型失败: ${err.message}`)
  }
}


function initFormData() {
  console.log('初始化表单数据，记录:', props.record)
  console.log('字段定义:', props.fields)

  if (props.mode == 'edit') {
    isEdit.value = true;
    recordId.value = props.record.id;
    console.log("初始化记录id", recordId.value)
  }
  else
  {
    props.mode='create'
    isEdit.value=false;
    recordId.value=null;
  }
  // 根据字段定义初始化数据
  const initialData = {}
  props.fields.forEach(field => {
    initialData[field.name] = props.record[field.name] || ''
  })

  console.log('初始化的表单数据:', initialData)
  formData.value = initialData
}

function fillFormData(record) {
  console.log('填充表单数据，记录:', record)

  if (!record || typeof record !== 'object') {
    console.warn('记录无效，无法填充表单')
    return
  }

  // 创建新的表单数据对象
  const newFormData = {}

  // 先确保所有字段都有默认值
  fields.value.forEach(field => {
    newFormData[field.name] = getDefaultValue(field.type)
  })

  // 填充API返回的字段
  Object.keys(record).forEach(key => {
    // 如果字段在模型中定义，使用它
    const field = fields.value.find(f => f.name === key)
    if (field) {
      const value = record[key]
      console.log(`设置字段 ${key} 的值:`, value)
      newFormData[key] = convertValueByType(value, field.type)
    }
  })

  console.log('填充后的表单数据:', newFormData)

  // 更新表单数据
  formData.value = newFormData
}

function convertValueByType(value, type) {
  if (value === null || value === undefined) {
    return getDefaultValue(type)
  }

  switch (type) {
    case 'string':
    case 'text':
    case 'email':
      return String(value)

    case 'number':
    case 'float':
      return parseFloat(value) || 0

    case 'integer':
      return parseInt(value) || 0

    case 'boolean':
      return Boolean(value)

    case 'date':
    case 'datetime':
      return value ? new Date(value) : null

    default:
      return value
  }
}

function generateFormRules() {
  const rules = {}

  fields.value.forEach(field => {
    const fieldRules = []

    // 必填字段验证
    if (field.required) {
      fieldRules.push({
        required: true,
        message: `${field.displayName || field.name}不能为空`,
        trigger: 'blur'
      })
    }

    // 根据字段类型添加验证规则
    switch (field.type) {
      case 'string':
      case 'text':
        // 可以添加字符串长度验证等
        break

      case 'integer':
      case 'number':
        fieldRules.push({
          type: 'number',
          message: `${field.displayName || field.name}必须是数字`,
          trigger: 'blur'
        })
        break

      case 'email':
        fieldRules.push({
          type: 'email',
          message: '请输入正确的邮箱格式',
          trigger: 'blur'
        })
        break

      // 可以添加更多类型的验证规则
    }

    if (fieldRules.length > 0) {
      rules[field.name] = fieldRules
    }
  })

  console.log('生成表单验证规则:', rules)
  rules.value = rules
}

function getDefaultValue(type) {
  switch (type) {
    case 'string':
    case 'text':
    case 'email':
      return ''
    case 'number':
    case 'integer':
    case 'float':
      return null
    case 'boolean':
      return false
    case 'date':
    case 'datetime':
      return null
    default:
      return null
  }
}

const testConnection = async () => {
  if (!formData.value.deviceip) {
    ElMessage.warning('请先输入IP地址')
    return
  }

  try {
    loading.value = true
    // 模拟测试连接
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('连接成功')
  } catch (error) {
    ElMessage.error('连接失败')
  } finally {
    loading.value = false
  }
}


const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true
    console.log('提交表单数据:', formData.value)

    // 处理表单数据，确保格式正确
    const processedData = processFormData(formData.value)
    console.log('处理后的表单数据:', processedData)
    try {
      // 添加超时处理
      const controller = new AbortController()
      const timeoutId = setTimeout(() => controller.abort(), 10000) // 10秒超时

      if (isEdit.value) {
        await dataStore.updateRecord(
          modelName.value,
          recordId.value,
          processedData
        )
      }
     if(!isEdit.value) {
        await dataStore.createRecord(
          modelName.value,
          processedData
        )
        console.log("create")
        emit("create");
      }

      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      // 返回列表页
      emit("submit");
     
      //router.push(`/data/${modelName.value}`)
      console.log(`/data/${modelName.value}`);
    } catch (err) {
      console.error('API请求失败:', err)

      // 处理超时错误
      if (err.name === 'AbortError') {
        throw new Error('请求超时，请稍后重试')
      }

      throw err
    }
  } catch (err) {
    console.error('表单提交失败:', err)

    // 提取错误消息
    let errorMessage = '保存失败'

    if (err.response) {
      // 服务器返回了错误响应
      errorMessage += `: ${err.response.status} ${err.response.statusText}`

      if (err.response.data && err.response.data.error) {
        errorMessage += ` - ${err.response.data.error}`
      } else if (err.response.data && err.response.data.message) {
        errorMessage += ` - ${err.response.data.message}`
      } else if (typeof err.response.data === 'string') {
        // 尝试提取错误消息
        try {
          const errorText = err.response.data.substring(0, 200) // 限制长度
          errorMessage += ` - ${errorText}`
        } catch (e) {
          // 忽略解析错误
        }
      }
    } else if (err.request) {
      // 请求已发送但没有收到响应
      errorMessage += ': 服务器无响应，请检查网络连接'
    } else if (err.message) {
      // 请求设置时出错
      errorMessage += `: ${err.message}`
    }

    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
    emit("submit");
  }
}

function processFormData(data) {
  const processed = {}

  // 遍历字段
  fields.value.forEach(field => {
    const { name, type } = field
    const value = data[name]

    // 跳过id字段（如果是创建模式）
    if (!isEdit.value && name === 'id') {
      console.log(`跳过id字段，因为是创建模式`)
      return
    }

    // 根据字段类型处理值
    switch (type) {
      case 'string':
      case 'text':
        // 确保字符串值不是null或undefined
        processed[name] = value === null || value === undefined ? '' : String(value)
        break

      case 'integer':
        // 确保整数值是有效的数字
        if (value === null || value === undefined || value === '') {
          processed[name] = 0
        } else {
          const intValue = parseInt(value)
          processed[name] = isNaN(intValue) ? 0 : intValue
        }
        break

      case 'number':
      case 'float':
        // 确保浮点数值是有效的数字
        if (value === null || value === undefined || value === '') {
          processed[name] = 0
        } else {
          const floatValue = parseFloat(value)
          processed[name] = isNaN(floatValue) ? 0 : floatValue
        }
        break

      case 'boolean':
        // 确保布尔值是true或false
        processed[name] = !!value
        break

      case 'date':
      case 'datetime':
        // 处理日期值
        if (value instanceof Date) {
          processed[name] = value.toISOString()
        } else if (value) {
          processed[name] = String(value)
        } else {
          processed[name] = null
        }
        break

      default:
        // 默认处理
        processed[name] = value === null || value === undefined ? null : value
    }
  })

  // 如果是编辑模式，确保包含ID
  if (isEdit.value && recordId.value) {
    console.log(`添加id字段，因为是编辑模式: ${recordId.value}`)
    processed.id = recordId.value
  }

  return processed
}

function retryLoading() {
  loadData()
}

// 监听记录变化
watch(() => props.record, (newRecord) => {
  console.log('记录数据更新:', newRecord)
  if (newRecord) {
    recordId.value = newRecord.id;
    console.log("记录", recordId.value)
    initFormData()
  }
}, { immediate: true, deep: true })

// 监听字段变化
watch(() => props.fields, (newFields) => {
  console.log('字段定义更新:', newFields)
  initFormData()
}, { immediate: true, deep: true })

// 组件挂载
onMounted(() => {
  console.log('组件挂载')
  initFormData()
})
</script>

<style scoped>
.data-form {
  padding: 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.error-card,
.loading-card,
.form-card {
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px 0;
}

.error-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.debug-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.debug-info h4 {
  margin-top: 0;
  margin-bottom: 10px;
}

.debug-info pre {
  background-color: #f1f3f5;
  padding: 10px;
  border-radius: 4px;
  overflow: auto;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
}

.el-button {
  margin-left: 10px;
}
</style>